// Profile JavaScript Document

// Checks given parameters are different than those in the session
function CheckSimilarValues(attribute, value)
{
	if ((attribute == "name") && (value == sessionStorage.name))
	{
		return true;
	}
	if ((attribute == "password") && (value == "********"))
	{
		return true;
	}
	if ((attribute == "photosrc") && (value == sessionStorage.photoSrc))
	{
		return true;
	}
	return false;
}

// Save Profile
function SaveProfile(attribute, value)
{
	// check parameters have been changed. If not, get out of here.
	// should alleviate false or accidental selection
	var similar = CheckSimilarValues(attribute, value);
	if (similar)
	{
		return;
	}
	
	// parameters for saving the given value into the given attribute 
	var form = "?email=" + sessionStorage.user + "&action=save&attribute=" + attribute + "&value=" + value;
	
	$.post("../UserManager" + form, function(data, status)
	{
		// if the action was successful, update the page
		if (status == "success")
		{
			if (attribute == "name")
			{
				sessionStorage[attribute] = value;
				$("#profile_name").text("Name: \"" + value + "\"");
			}
			if (attribute == "password")
			{
				$("#profile_password").text("New Password Saved.");
			}
			$.post("../XMLDump&refresh=true");
		}
		else
		{
			alert("There was an error saving your data. Try again or exit edit mode.");
		}
	});
}

// Edit Profile
function EditProfile()
{
	// Change header to indicate edit mode.
	$("#profile_header").text("Editing Profile... (Selecting any field allows editing. Deselecting will save.)");
	
	// Set up the name edit line
	var name = $("#profile_name").text();
	var nameStart = name.indexOf("\"", 6) + 1;
	var nameEnd = name.indexOf("\"", nameStart);
	name = name.substring(nameStart, nameEnd);
	$("#profile_name").html("Name:</br><input type=\"text\" value=\"" + name + "\" " +
							"onblur=\"SaveProfile('name', this.value)\" />");
	$("#profile_password").html("Password:</br><input type=\"password\" value=\"********\" " +
								"onblur=\"SaveProfile('password', this.value)\" />");
	$("#profile_photosrc").html("<form id=\"photo_upload_form\" method=\"POST\" action=\"../UserManager\" enctype=\"multipart/form-data\">Upload New Photo...<br/><br/><br/>" +
								"<input type=\"file\" name=\"file\" id=\"photoFile\" /><br/>" +
								"<input type=\"text\" name=\"email\" value=\"" + sessionStorage.user + "\" hidden /><br/>" +
								"<input type=\"text\" name=\"action\" value=\"savephoto\" hidden /><br/>" +
								"<input type=\"submit\" value=\"Upload\" name=\"photoUpload\" id=\"photoUpload\" /><br/>" + 
								"</form>");
	$("#photo_upload_form").ajaxForm({data: $("photo_upload_form").serialize(),
						  	url : '../UserManager', 
						  	success : function(data, status, jqXHR)
						  	{
						  		if (status == "success")
						  		{
						  			data = "../resources/userphotos/" + data;
						  			sessionStorage.photoSrc = data;
						  			var photoWidth = $("#profile_photosrc").innerWidth() - 20;
						  			var photoHeight = $("#profile_photosrc").innerHeight() - 20;
						  			var photoimg = "<img src=\"" + data + "\" " + 
						  			"width=\"" + photoWidth + "px\" " +
						  			"height=\"" + photoHeight + "px\" />";
						  			$("#profile_photosrc").html(photoimg);
						  			$.post("../XMLDump&refresh=true");
						  			ReadPhoto();
						  			return true;
						  		}
						  	}
		}).submit(function() { $(this).ajaxSubmit(); return false; });
	$("#profile_edit_button").html("Exit Edit Mode...").mouseup(LoadProfile);
}

// Delete Profile
function DeleteProfile()
{
	$.post("../UserManager?action=deleteuser&email=" + sessionStorage.user, function(data, status)
	{
		if (status == "success")
		{
			$.post("../XMLDump&refresh=true");
			$("#logoutlink").mouseup();
		}
	});
}

// Show all users
function AllUsers()
{
	$.get("../UserManager?action=getusers&email=" + sessionStorage.user, function(data, status)
	{
		if (status == "success")
		{
			alert("All Users:\n" + data);
		}
	});
}

function GetPosts()
{
	var postsRegistered = [];
	var postsCreated = [];
	var email = sessionStorage.user;
	
	$.get("../PostManager?action=getpostsbyuser&email=" + email, function(data, status)
	{
		if ((status == "success") && (data != "error"))
		{
			postsRegistered = data.split("\n");			
			$.get("../UserManager?action=getposts&email=" + email, function(data, status)
			{
				if (status == "success")
				{
					for (var i = 0; i < postsRegistered.length; i++)
					{
						postsCreated[i] = false;
					}
					var myPosts = ((data != "") ? data.split("\n") : []);
					var i = 0;
					while (i < myPosts.length)
					{
						var myPostId = myPosts[i].split(",")[0];
						for (var j = 0; j < postsRegistered.length; j++)
						{
							var regPostId = postsRegistered[j].split(",")[0];
							if (myPostId == regPostId)
							{
								postsCreated[j] = true;
								i++;
							}
						}
					}
					if (postsRegistered.length > 0)
					{
						var tasks = $("#profile_tasks_table tbody");
						var teams = $("#profile_teams_table tbody");

						for (var i = 0; i < postsRegistered.length; i++)
						{
							var post = postsRegistered[i].split(",");
							if (postsCreated[i])
							{
								post[post.length] = "(I Created This!)";
							}
							var side;
							if (post[2] == "0")
							{
								side = tasks;
							}
							else
							{
								side = teams;
							}
							side.append("<tr><td>" + post.join().replace(/,/g," | ") + "</td></tr>\n");
						}
					}
				}
			});
		}
	});
}

//Load User Profile
function LoadUserProfile()
{
	// Set table CSS
	//var width = $("#content_holder").innerWidth();
	//var height = $("#content_holder").innerHeight();
	$("#profile_container").css({"width" : "95%", "height" : "95%"});
	$("#profile_table td").css("padding", "10px");
	$("#profile_table th").css({"text-decoration" : "underline", "font-weight" : "bold"});
	$(".middle").css({"vertical-align" : "middle", "text-align" : "center"});
	$("#profile_name").css({"width" : "24%", "height" : "auto"});
	$("#profile_edit").css({"width" : "24%", "height" : "auto"});
	$("#profile_photosrc").css({"width" : "48%", "height" : "auto"});
	$("#profile_events_table").css({"width" : "95%", "height" : "95%"});
	
	// Set buttons animation
	var buttons = ["#profile_edit_button", "#profile_delete_button", "#profile_all_users_button"];
	
	for (elem in buttons)
	{
		$(buttons[elem])
			.mousedown(function(e) 
			{
				OnMouseDown(this.id);
			})
			.mouseup(function(e)
			{
				OnMouseUp(this.id);
			})
			.mouseout(function(e)
			{
				OnMouseOut(this.id);
			});
	}
	
	$("#profile_edit_button").mouseup(EditProfile);
	$("#profile_delete_button").mouseup(DeleteProfile);
	$("#profile_all_users_button").mouseup(AllUsers);

	// Set Profile Details	
	$("#profile_name").append(" \"").append(sessionStorage.name).append("\"");
	$("#profile_email").append(sessionStorage.user);
	var photoWidth = $("#profile_photosrc").innerWidth() - 20;
	var photoHeight = $("#profile_photosrc").innerHeight() - 20;
	var photosrc = sessionStorage.photoSrc;
	if ((photosrc != null) && (photosrc != "null"))
	{
		var photoimg = "<img src=\"" + photosrc + "\" " + 
						"width=\"" + photoWidth + "px\" " +
						"height=\"" + photoHeight + "px\" />";
		$("#profile_photosrc").html(photoimg);
	}
	
	// TODO write get posts for profile
	GetPosts();
}
